﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using NurseStation.common;
using NurseStation.views;
using Prism.Events;
using Prism.Ioc;
using Prism.Commands;
using SqlSugar;
using NurseStation.DataModels;
using NurseStation.Services;
using Prism.Regions;
using System.Linq;
using Unity.Resolution;
namespace NurseStation.viewmodels
{
    /// <summary>
    /// 批量录入ViewModel
    /// </summary>
    public class BatchVitalSignViewModel : VmBase, INavigationAware
    {

        readonly Notifiaction notifiaction = Notifiaction.Instance;
        NurseDayWorkService nurseDayWorkService = new NurseDayWorkService();

        /// <summary>
        /// 主控件
        /// </summary>
        public Grid MainGrid = null;

        /// <summary>
        /// 列表控件  2023-05-24
        /// </summary>
        public DataGrid dataGrid { get; set; }

        #region 属性

  
        private DateTime _ChooseDATE;
        /// <summary>
        /// 选择的录入时间  2023-05-24
        /// </summary>
        public DateTime ChooseDATE
        {
            get
            {
                return _ChooseDATE;
            }
            set
            {
                _ChooseDATE = value;
                LoadData();
                RaisePropertyChanged("ChooseDATE");
            }
        }

        private List<NurseDayWork> _AllNurseDayWork;
        /// <summary>
        /// DataGrid绑定列表数据  2023-05-24
        /// </summary>
        public List<NurseDayWork> AllNurseDayWork
        {
            get
            {
                return _AllNurseDayWork;
            }
            set
            {
                _AllNurseDayWork = value;
                RaisePropertyChanged("AllNurseDayWork");
            }
        }

        private NurseDayWork _CurrVitSign;
        /// <summary>
        /// 当前选中列表数据  2023-05-24
        /// </summary>
        public NurseDayWork CurrVitSign
        {
            get
            {
                return _CurrVitSign;
            }
            set
            {
                _CurrVitSign = value;

                RaisePropertyChanged("CurrVitSign");
            }
        }


        private Action<dynamic> cellEditing;
        /// <summary>
        /// 单元格编辑事件  2022-04-20
        /// </summary>
        public Action<dynamic> CellEditing
        {
            get { return cellEditing; }
            set { cellEditing = value; RaisePropertyChanged(nameof(CellEditing)); }
        }

        private DataTemplate _BatchVitalSignDataTemplate;
        /// <summary>
        /// 批量录入主题模板 
        /// </summary>
        public DataTemplate BatchVitalSignDataTemplate
        {
            get => _BatchVitalSignDataTemplate;
            set
            {
                _BatchVitalSignDataTemplate = value;
                RaisePropertyChanged(nameof(BatchVitalSignDataTemplate));
            }
        }

        private Visibility _ColSetVis = Visibility.Collapsed;
        /// <summary>
        /// 是否允许修改列
        /// </summary>
        public Visibility ColSetVis
        {
            get
            {
                return _ColSetVis;
            }
            set
            {
                _ColSetVis = value;
                RaisePropertyChanged(nameof(ColSetVis));
            }
        }


        /// <summary>
        /// 界面加载完毕
        /// </summary>
        public DelegateCommand<object> LoadedWindowCommand { get; set; }

        /// <summary>
        /// 搜索命令  2023-05-24
        /// </summary>
        public DelegateCommand<object> CreateCommand { get; set; }
        /// <summary>
        /// 搜索命令  2023-05-24
        /// </summary>
        public DelegateCommand<object> SerchCommand { get; set; }


        /// 改变搜索条件命令  2023-05-24
        /// </summary>
        public DelegateCommand<object> ChangeCommand { get; set; }


        /// <summary>
        /// 导出命令 2022-05-26 
        /// </summary>
        public DelegateCommand<object> OutPutCommad { get; private set; }

        /// <summary>
        /// 导出年汇总
        /// </summary>
        public DelegateCommand<object> OutPutYearCommad { get; private set; }
        #endregion


        /// <summary>
        /// 构造方法  2023-05-24
        /// </summary>
        /// <param name="container"></param>
        /// <param name="eventAggregator"></param>
        public BatchVitalSignViewModel(IContainerExtension container, IEventAggregator eventAggregator) : base(container, eventAggregator)
        {
            this.BatchVitalSignDataTemplate = ThemeHelper.GetDataTemplate("BatchVitalSignViewThemes");
            this.LoadedWindowCommand = new DelegateCommand<object>(OnLoaded);
            this.SerchCommand = new DelegateCommand<object>(OnSerch);
            this.ChangeCommand = new DelegateCommand<object>(OnChangeCommand);
            this.OutPutCommad = new DelegateCommand<object>(OnOutPut);
            this.CreateCommand = new DelegateCommand<object>(OnCreate);
            this.OutPutYearCommad = new DelegateCommand<object>(OnOutPutYear);
            CellEditing = OnCellEditing;
            LoadTheme();
            _ChooseDATE = DateTime.Now;
            RaisePropertyChanged("ChooseDATE");
            if (StringResourceHelper.GetXamlSetting().ColSetEnable)
            {
                ColSetVis = Visibility.Visible;
            }
        }

        /// <summary>
        /// 单元格编辑事件  2022-04-20
        /// 弹出框支持弹出指定View  2023-05-19
        /// </summary>
        /// <param name="obj"></param>
        private void OnCellEditing(dynamic obj)
        {
            if ("Save".Equals(obj.Command))
            {
                try
                {
                    var dt = obj.Data as NurseDayWork;
                    if (dt != null)
                    {
                        if (nurseDayWorkService.UpdateByEditCol(dt))
                        {
                            notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "保存成功！", NotifiactionType = EnumPromptType.Success });
                        }
                        else
                        {
                            notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "保存失败！", NotifiactionType = EnumPromptType.Error });
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.GetLogHelper().Error("保存数据出错" + ex);
                }
            }
        }

        /// <summary>
        /// 刷新列表  2023-05-24
        /// </summary>
        /// <param name="arg"></param>
        void OnSerch(object arg)
        {
            LoadData();
        }

        public void OnLoaded(object o)
        {
            OnSerch(null);
        }


        /// <summary>
        /// 整合数据，实体处理加载  2023-05-24
        /// </summary>
        private void LoadData(bool showMsg = true)
        {
            try
            {
                string GroupName = ChooseDATE.ToString("yyyy-MM");
                Expressionable<NurseDayWork> exp = Expressionable.Create<NurseDayWork>();
                exp.And(it => it.GROUPNAME == GroupName);
                List<NurseDayWork> Copy = nurseDayWorkService.GetListByWhere(exp);
                if (Copy.Count > 0)
                {
                    NurseDayWork sumn = new NurseDayWork();
                    for (int i = Copy.Count - 1; i >= 0; i--)
                    {
                        if (Copy[i].IS_SUM == 1)
                        {
                            Copy.Remove(Copy[i]);
                            continue;
                        }
                        sumn.C1 = (TriageEx.GetNum(sumn.C1) + TriageEx.GetNum(Copy[i].C1)).ToString();
                        sumn.C2 = (TriageEx.GetNum(sumn.C2) + TriageEx.GetNum(Copy[i].C2)).ToString();
                        sumn.C3 = (TriageEx.GetNum(sumn.C3) + TriageEx.GetNum(Copy[i].C3)).ToString();
                        sumn.C4 = (TriageEx.GetNum(sumn.C4) + TriageEx.GetNum(Copy[i].C4)).ToString();
                        sumn.C5 = (TriageEx.GetNum(sumn.C5) + TriageEx.GetNum(Copy[i].C5)).ToString();
                        sumn.C6 = (TriageEx.GetNum(sumn.C6) + TriageEx.GetNum(Copy[i].C6)).ToString();
                        sumn.C7 = (TriageEx.GetNum(sumn.C7) + TriageEx.GetNum(Copy[i].C7)).ToString();
                        sumn.C8 = (TriageEx.GetNum(sumn.C8) + TriageEx.GetNum(Copy[i].C8)).ToString();
                        sumn.C9 = (TriageEx.GetNum(sumn.C9) + TriageEx.GetNum(Copy[i].C9)).ToString();
                        sumn.C10 = (TriageEx.GetNum(sumn.C10) + TriageEx.GetNum(Copy[i].C10)).ToString();
                        sumn.C11 = (TriageEx.GetNum(sumn.C11) + TriageEx.GetNum(Copy[i].C11)).ToString();
                        sumn.C12 = (TriageEx.GetNum(sumn.C12) + TriageEx.GetNum(Copy[i].C12)).ToString();
                        sumn.C13 = (TriageEx.GetNum(sumn.C13) + TriageEx.GetNum(Copy[i].C13)).ToString();
                        sumn.C14 = (TriageEx.GetNum(sumn.C14) + TriageEx.GetNum(Copy[i].C14)).ToString();
                        sumn.C15 = (TriageEx.GetNum(sumn.C15) + TriageEx.GetNum(Copy[i].C15)).ToString();
                        sumn.C16 = (TriageEx.GetNum(sumn.C16) + TriageEx.GetNum(Copy[i].C16)).ToString();
                        sumn.C17 = (TriageEx.GetNum(sumn.C17) + TriageEx.GetNum(Copy[i].C17)).ToString();
                        sumn.C18 = (TriageEx.GetNum(sumn.C18) + TriageEx.GetNum(Copy[i].C18)).ToString();
                        sumn.C19 = (TriageEx.GetNum(sumn.C19) + TriageEx.GetNum(Copy[i].C19)).ToString();
                        sumn.C20 = (TriageEx.GetNum(sumn.C20) + TriageEx.GetNum(Copy[i].C20)).ToString();
                        sumn.C21 = (TriageEx.GetNum(sumn.C21) + TriageEx.GetNum(Copy[i].C21)).ToString();
                        sumn.C22 = (TriageEx.GetNum(sumn.C22) + TriageEx.GetNum(Copy[i].C22)).ToString();
                        sumn.C23 = (TriageEx.GetNum(sumn.C23) + TriageEx.GetNum(Copy[i].C23)).ToString();
                        sumn.C24 = (TriageEx.GetNum(sumn.C24) + TriageEx.GetNum(Copy[i].C24)).ToString();
                        sumn.C25 = (TriageEx.GetNum(sumn.C25) + TriageEx.GetNum(Copy[i].C25)).ToString();
                        sumn.C26 = (TriageEx.GetNum(sumn.C26) + TriageEx.GetNum(Copy[i].C26)).ToString();
                        sumn.C27 = (TriageEx.GetNum(sumn.C27) + TriageEx.GetNum(Copy[i].C27)).ToString();
                        sumn.C28 = (TriageEx.GetNum(sumn.C28) + TriageEx.GetNum(Copy[i].C28)).ToString();
                        sumn.C29 = (TriageEx.GetNum(sumn.C29) + TriageEx.GetNum(Copy[i].C29)).ToString();
                        sumn.C30 = (TriageEx.GetNum(sumn.C30) + TriageEx.GetNum(Copy[i].C30)).ToString();
                        sumn.C31 = (TriageEx.GetNum(sumn.C31) + TriageEx.GetNum(Copy[i].C31)).ToString();
                        sumn.C32 = (TriageEx.GetNum(sumn.C32) + TriageEx.GetNum(Copy[i].C32)).ToString();
                        sumn.C33 = (TriageEx.GetNum(sumn.C33) + TriageEx.GetNum(Copy[i].C33)).ToString();
                        sumn.C34 = (TriageEx.GetNum(sumn.C34) + TriageEx.GetNum(Copy[i].C34)).ToString();
                        sumn.C35 = (TriageEx.GetNum(sumn.C35) + TriageEx.GetNum(Copy[i].C35)).ToString();
                        sumn.C36 = (TriageEx.GetNum(sumn.C36) + TriageEx.GetNum(Copy[i].C36)).ToString();
                        sumn.C37 = (TriageEx.GetNum(sumn.C37) + TriageEx.GetNum(Copy[i].C37)).ToString();
                        sumn.C38 = (TriageEx.GetNum(sumn.C38) + TriageEx.GetNum(Copy[i].C38)).ToString();
                        sumn.C39 = (TriageEx.GetNum(sumn.C39) + TriageEx.GetNum(Copy[i].C39)).ToString();
                        sumn.C40 = (TriageEx.GetNum(sumn.C40) + TriageEx.GetNum(Copy[i].C40)).ToString();
                        sumn.IS_SUM = 1;
                    }
                    Copy.Add(sumn);
                }
                AllNurseDayWork = Copy;
                if (showMsg)
                    notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "数据已刷新！", NotifiactionType = EnumPromptType.Success });
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error("加载报错：" + ex.ToString());
            }
        }



        #region 命令处理方法

        /// <summary>
        /// 调整列
        /// </summary>
        /// <param name="o"></param>
        private void OnChangeCommand(object o)
        {
            var colSetting = container.Resolve<ColSetting>();
            if (colSetting.ShowDialog() == true)
            {
                BatchVitalSignDataTemplate = ThemeHelper.Instance.GetDataTemplateFromXml();
                LoadData();
            }
        }

        /// <summary>
        /// 改变主题
        /// </summary>
        private void LoadTheme()
        {
            try
            {
                string CurrTheme = "BatchVitalSignViewThemes";
                DataTemplate tempDT = ThemeHelper.GetDataTemplate(CurrTheme);
                BatchVitalSignDataTemplate = tempDT;
            }
            catch (Exception e)
            {
                LogHelper.GetLogHelper().Error("设置主题错误：" + e.Message);
            }
        }

        /// <summary>
        /// 根据选择月份，补全空日期行
        /// </summary>
        /// <param name="obj"></param>
        public void OnCreate(object obj)
        {
            string GroupName = ChooseDATE.ToString("yyyy-MM");
            Expressionable<NurseDayWork> exp = Expressionable.Create<NurseDayWork>();
            exp.And(it => it.GROUPNAME == GroupName);
            List<NurseDayWork> getList1 = nurseDayWorkService.GetListByWhere(exp);
            List<DateTime> hasTime = getList1.Select(c => c.RECORD_TIME)?.ToList();
            DateTime StartDate = new DateTime(ChooseDATE.Year, ChooseDATE.Month, 1); // 获取当前月的最后一天
            DateTime EndDate = new DateTime(ChooseDATE.Year, ChooseDATE.Month, 1).AddMonths(1).AddDays(-1); // 获取当前月的最后一天
            List<NurseDayWork> tempList = new List<NurseDayWork>();
            int days = (EndDate - StartDate).Days;
            for (int ip = 0; ip <= days; ip++)
            {
                DateTime tempRec = StartDate.AddDays(ip);
                if (!hasTime.Contains(tempRec))
                {
                    NurseDayWork tempRow = new NurseDayWork();
                    tempRow.IS_SUM = 0;
                    tempRow.CREATE_TIME = DateTime.Now;
                    tempRow.RECORD_TIME = tempRec;
                    tempRow.GROUPNAME = GroupName;
                    tempList.Add(tempRow);
                }
            }
            if (tempList.Count > 0)
            {
                List<long> list = nurseDayWorkService.Insertable(tempList);
                if (list.Count > 0)
                {
                    LoadData(false);
                    notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "生成成功！", NotifiactionType = EnumPromptType.Success });
                }
                else
                {
                    notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "生成失败！", NotifiactionType = EnumPromptType.Error });
                }
            }
            else
            {
                notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "当前月份数据无缺失！", NotifiactionType = EnumPromptType.Warn });
            }
        }

        /// <summary>
        /// 导出患者列表数据  2023-05-25 
        /// </summary>
        /// <param name="obj"></param>
        public void OnOutPut(object obj)
        {
            var regTxtList = MyVisualTreeHelper.FindVisualChildren<DataGrid>(MainGrid).ToList();
            if (regTxtList != null && regTxtList.Count() > 0)
            {
                this.dataGrid = regTxtList[0];
            }
            if (dataGrid != null)
            {
                List<ColShow> listCol = nurseDayWorkService.GetDictCol().FindAll(c=>c.IfShow=="是");
                DataTable dt = new DataTable();
                //列添加
                dt.Columns.Add(new DataColumn() { ColumnName = "日 期" });
                for (int i = 0; i < listCol.Count; i++)
                {
                    DataColumn column = new DataColumn();
                    column.ColumnName = listCol[i].Header;
                    dt.Columns.Add(column);
                }
                //行添加
                for (int i = 0; i < AllNurseDayWork.Count; i++)
                {
                    DataRow dr = dt.NewRow();

                    if (AllNurseDayWork[i].IS_SUM == 1)
                    {
                        dr[0] = "合计:";
                    }
                    else
                    {
                        dr[0] = AllNurseDayWork[i].RECORD_TIME.ToString("yyy-MM-dd");
                    }

                    for (int li = 0; li < listCol.Count; li++)
                    {
                        string filedName = listCol[li].FieldName;
                        dr[li+1] = TriageEx.FindProValue<string>(filedName, AllNurseDayWork[i]);
                    }
                    dt.Rows.Add(dr);
                }
                System.Windows.Forms.SaveFileDialog dialog1 = new System.Windows.Forms.SaveFileDialog();
                dialog1.FileName = string.Concat(new string[]
                {
                     Environment.GetFolderPath(Environment.SpecialFolder.Desktop),  "\\查询数据", ".xls"
                });
                dialog1.Filter = @"xls files(*.xls)|*.xls";
                if (dialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ExcelHelper.Export(dt, string.Concat(new string[] { "查询数据" }), dialog1.FileName);
                }
                notifiaction.AddNotifiaction(new NotifiactionModel() { Title = "提示", Content = "查询数据已导出！", NotifiactionType = EnumPromptType.Success });

            }
        }

        /// <summary>
        /// 统计当年数据
        /// </summary>
        /// <param name="obj"></param>
        public void OnOutPutYear(object obj)
        {
            MessageBoxResult result = MessageBox.Show($"确定要汇总{ChooseDATE.ToString("yyyy")}年的数据吗？", "请确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                DataForYearViewModel viewModel = new DataForYearViewModel(container, eventAggregator, regionManager);
                viewModel.ChooseDATE = ChooseDATE;
                DataForYear year1 = new DataForYear(viewModel);
                year1.ShowDialog();
            }
        }
        #endregion


        #region 接口实现方法-导航相关

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
        }
        #endregion
    }

}